import express from 'express'
import cors from 'cors'

const app = express()
app.use(cors())
app.use(express.json())

const PORT = process.env.PORT || 8787
const COZE_API_TOKEN = process.env.COZE_API_TOKEN || ''
const COZE_API_BASE = process.env.COZE_API_BASE || 'https://api.coze.cn'
const COZE_CHAT_PATH = process.env.COZE_CHAT_PATH || '/v1/chat'
const BOT_ID = process.env.COZE_BOT_ID || ''

app.post('/coze/chat', async (req, res) => {
  try {
    if (!COZE_API_TOKEN) return res.status(500).json({ error: 'Missing COZE_API_TOKEN' })
    if (!BOT_ID) return res.status(500).json({ error: 'Missing COZE_BOT_ID' })
    const { text, conversationId } = req.body || {}
    if (!text || typeof text !== 'string') {
      return res.status(400).json({ error: 'Invalid text' })
    }

    const url = `${COZE_API_BASE}${COZE_CHAT_PATH}`
    const body = {
      bot_id: BOT_ID,
      query: text,
      conversation_id: conversationId || undefined,
    }

    const resp = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${COZE_API_TOKEN}`,
      },
      body: JSON.stringify(body),
    })

    if (!resp.ok) {
      const t = await resp.text()
      return res.status(resp.status).json({ error: 'Coze error', detail: t })
    }

    const data = await resp.json()

    let answer = ''
    if (data && typeof data === 'object') {
      if (data.answer && typeof data.answer === 'string') answer = data.answer
      else if (data.data && data.data.answer) answer = data.data.answer
    }
    if (!answer) answer = '已收到请求但未解析到答案'

    const returnedConvId = data?.conversation_id || data?.data?.conversation_id || conversationId || null
    return res.json({ answer, raw: data, conversationId: returnedConvId })
  } catch (err) {
    return res.status(500).json({ error: 'Proxy error' })
  }
})

app.listen(PORT, () => {
  console.log(`Server listening on http://localhost:${PORT}`)
})
